<template>
  <div class="mod-prod-sku-table">
    <el-form-item :label="this.$i18n.t('product.priceAndInventory')" :label-width="this.$i18n.t('language') === 'English'?'132px':'100px'">
      <!--      批量设置-->
      <div>
        <el-button
          type="text"
          icon="el-icon-document-checked"
          size="small"
          @click="switchSet"
        >{{$t("groups.batchSettings")}}</el-button>
        <el-form :inline="true" class="demo-form-inline" v-if="isEdit">
          <el-form-item :label="this.$i18n.t('live.marketPrice')">
            <el-input-number v-model="dataFrom.oriPrice"
                             controls-position="right"
                             size="small"
                             :precision="2"
                             :max="1000000000"
                             :min="0"
            ></el-input-number>
          </el-form-item>
          <el-form-item :label="this.$i18n.t('product.sellingPrice')">
            <el-input-number v-model="dataFrom.price"
                             controls-position="right"
                             size="small"
                             :precision="2"
                             :max="1000000000"
                             :min="0"
            ></el-input-number>
          </el-form-item>
          <el-form-item :label="this.$i18n.t('coupon.stock')">
            <el-input-number v-model="dataFrom.stocks"
                             controls-position="right"
                             :disabled="isCompose == 1"
                             size="small"
                             :precision="0"
                             :max="9999999"
                             :min="0"
            ></el-input-number>
          </el-form-item>
          <el-form-item :label="this.$i18n.t('product.commodityWeight')">
            <el-input-number v-model="dataFrom.weight"
                             controls-position="right"
                             size="small"
                             :precision="2"
                             :max="1000000000"
                             :min="0"
            ></el-input-number>
          </el-form-item>
          <el-form-item :label="this.$i18n.t('product.commodityVolume')">
            <el-input-number v-model="dataFrom.volume"
                             controls-position="right"
                             size="small"
                             :precision="2"
                             :max="1000000000"
                             :min="0"
            ></el-input-number>
          </el-form-item>
          <el-form-item>
            <el-button size="small" type="primary" @click="batchSet" class="filter-submitBtn">{{$t("crud.filter.submitBtn")}}</el-button>
          </el-form-item>
          <el-form-item>
            <el-button size="small" type="danger" @click="switchSet" class="filter-submitBtn">{{$t("crud.filter.cancelBtn")}}</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!--      sku列表-->
      <el-table
        :data="value"
        border
        style="margin-top: 20px"
        :header-cell-style="{background:'#f5f7fa','text-align':'center'}"
        :cell-style="{'text-align':'center'}"
      >
        <el-table-column
          v-for="(leftTitle, index) in tableLeftTitles"
          :key="index"
          :label="$t('language') === 'English' ? leftTitle.tagNameEn : leftTitle.tagName"
        >
          <template v-if="scope.row.propertiesEn && scope.row.properties" slot-scope="scope">{{$t('language') === 'English' ? scope.row.propertiesEn.split(';')[index].split(':')[1] : scope.row.properties.split(';')[index].split(':')[1]}}</template>
        </el-table-column>
        <el-table-column
          v-if="tableLeftTitles.length"
          prop="pic"
          :label="this.$i18n.t('product.skuPictures')"
          width="180"
        >
          <template slot-scope="scope">
            <img-upload v-model="scope.row.pic"></img-upload>
          </template>
        </el-table-column>
        <el-table-column
          prop="prodNameCn"
          :label="this.$i18n.t('product.prodNameCn')"
          width="250"
          v-if="tableLeftTitles.length"
        >
          <template slot-scope="scope">
            <el-input v-model="scope.row.prodNameCn" type="textarea" :disabled="!scope.row.status"></el-input>
          </template>
        </el-table-column>
        <el-table-column
          prop="prodNameEn"
          :label="this.$i18n.t('product.prodNameEn')"
          width="250"
          v-if="tableLeftTitles.length"
        >
          <template slot-scope="scope">
            <el-input v-model="scope.row.prodNameEn" type="textarea" :disabled="!scope.row.status"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="oriPrice" :label="this.$i18n.t('live.marketPrice')+this.$i18n.t('live.yuan')" width="160">
          <template slot-scope="scope">
            <el-input-number
              size="small"
              v-model="scope.row.oriPrice"
              controls-position="right"
              :precision="2"
              :max="1000000000"
              :min="0.01"
              :disabled="!scope.row.status"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="price" :label="this.$i18n.t('product.sellingPrice')+this.$i18n.t('live.yuan')" width="160">
          <template slot-scope="scope">
            <el-input-number
              size="small"
              v-model="scope.row.price"
              controls-position="right"
              :precision="2"
              :max="1000000000"
              :min="0.01"
              :disabled="!scope.row.status"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="stocks" :label="this.$i18n.t('coupon.stock')" width="160">
          <template slot-scope="scope">
            <el-input-number
              size="small"
              v-model="scope.row.stocks"
              controls-position="right"
              :precision="0"
              :max="9999999"
              :min="0"
              :disabled="!scope.row.status || isCompose == 1"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column
          prop="partyCode"
          :label="this.$i18n.t('product.commodityCode')"
          width="200"
        >
          <template slot-scope="scope">
            <el-input v-model="scope.row.partyCode" size="small" maxlength="100"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="weight" :label="this.$i18n.t('product.commodityWeight')" width="160">
          <template slot-scope="scope">
            <el-input-number
              size="small"
              v-model="scope.row.weight"
              controls-position="right"
              :precision="2"
              :max="1000000000"
              :min="0"
              :disabled="!scope.row.status"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="volume" :label="this.$i18n.t('product.commodityVolume')" width="160">
          <template slot-scope="scope">
            <el-input-number
              size="small"
              v-model="scope.row.volume"
              controls-position="right"
              :precision="2"
              :max="1000000000"
              :min="0"
              :disabled="!scope.row.status"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column
          :label="this.$i18n.t('text.menu')"
          :width="this.$i18n.t('language') === 'English' ? '210' : '120'"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="changeSkuStatus(`${scope.$index}`)"
              v-if="scope.row.status"
            >{{$t("publics.disable")}}</el-button>
            <el-button
              type="text"
              size="small"
              @click="changeSkuStatus(`${scope.$index}`)"
              v-else
            >{{$t("shop.ena")}}</el-button>
            <!-- {{scope.row.skuSingleProds != null ? '编辑关联单品' : '关联单品'}} -->
            <el-button
              type="text"
              size="small"
              @click="relationSkuRetailProd(scope.row, scope.$index)"
              v-if="isCompose === 1"
            >{{$t("product.relatedItems")}}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <!-- 弹窗, 关联单品的弹窗 -->
    <sku-single-prod
      v-if="relationVisible"
      ref="skuSingleProd"
      @refreshSelectSingleProds="selectSingleProds"
    ></sku-single-prod>
  </div>
</template>

<script>
// import PicUpload from '@/components/pic-upload'
import ImgUpload from '@/components/img-upload'
import SkuSingleProd from './sku-single-prod'
import Big from 'big.js'
export default {
  data () {
    return {
      // 数据库中的规格
      dbSpecs: [],
      // 根据选定的规格所查询出来的规格值
      dbSpecValues: [],
      specs: [], // 使用的规格
      initing: false,
      relationVisible: false,
      isEdit: false,
      dataFrom: {
        oriPrice: null,
        price: null,
        stocks: null,
        weight: null,
        volume: null
      }
    }
  },
  components: {
    ImgUpload,
    SkuSingleProd
  },
  props: {
    value: {
      default: [],
      type: Array
    },
    prodNameCn: {
      default: ''
    },
    prodNameEn: {
      default: ''
    },
    isCompose: {
      default: 0,
      type: Number
    }
  },
  watch: {
    prodNameCn: function () {
      this.skuAddProdName()
    },
    prodNameEn: function () {
      this.skuAddProdName()
    },
    rowSpan: function () {
      console.log(this.rowSpan)
    }
  },
  created: function () {
    this.isEdit = false
    this.$http({
      url: this.$http.adornUrl(`/prod/spec/list`),
      method: 'get',
      params: this.$http.adornParams()
    }).then(({ data }) => {
      this.dbSpecs = data
    })
    if (!this.value.length) {
      this.value.push({
        oriPrice: 0.01,
        partyCode: '',
        price: 0.01,
        prodName: '',
        status: 1,
        stocks: 0,
        volume: 0,
        weight: 0,
        isCompose: this.isCompose
      })
    }
  },
  computed: {
    tableLeftTitles () {
      let res = []
      for (let i = 0; i < this.skuTags.length; i++) {
        const skuTag = this.skuTags[i]
        res.push(skuTag)
      }
      return res
    },
    skuTags: {
      get () { return this.$store.state.prod.skuTags }
    },
    defalutSku () {
      return this.$store.state.prod.defalutSku
    }
  },
  methods: {
    init () {
      this.initing = true
    },
    getTableSpecData () {
      return this.value
    },
    tableSpanMethod ({ row, column, rowIndex, columnIndex }) {
    },
    changeSkuStatus (tagIndex) {
      this.value[tagIndex].status = this.value[tagIndex].status ? 0 : 1
    },
    skuAddProdName () {
      if (this.initing) {
        return
      }
      let skuList = []
      for (let i = 0; i < this.value.length; i++) {
        const sku = Object.assign({}, this.value[i])
        if (!sku.properties || !sku.propertiesEn) {
          return
        }
        sku.skuName = ''
        sku.skuNameEn = ''
        let properties = sku.properties.split(';')
        let propertiesEn = sku.propertiesEn.split(';')
        for (const propertiesKey in properties) {
          sku.skuName += properties[propertiesKey].split(':')[1] + ' '
        }
        for (const propertiesKey in propertiesEn) {
          sku.skuNameEn += propertiesEn[propertiesKey].split(':')[1] + ' '
        }
        sku.prodNameCn = this.prodNameCn + ' ' + sku.skuName
        sku.prodName = this.prodNameCn + ' ' + sku.skuName
        sku.prodNameEn = this.prodNameEn + ' ' + sku.skuNameEn
        skuList.push(sku)
      }
      this.$emit('input', skuList)
    },
    relationSkuRetailProd (row, index) {
      this.relationVisible = true
      this.$nextTick(() => {
        this.$refs.skuSingleProd.init(row, index)
      })
    },
    selectSingleProds (data, index) {
      console.log(data)
      console.log(index)
      let skuSingleProds = data.skuSingleProds
      data.stocks = this.countSkuStock(skuSingleProds)
      let price = this.countSkuPrice(skuSingleProds)
      data.price = price
      data.oriPrice = price
      this.value[index] = data
    },
    countSkuStock (skuSingleProds) {
      let stock = 0
      if (!skuSingleProds) {
        return stock
      }
      if (!skuSingleProds.length) {
        return stock
      }
      let arr = []
      skuSingleProds.forEach(element => {
        var x = new Big(element.stocks)
        var y = new Big(element.retailNums)
        var result = 0
        if (y > 0) {
          result = parseInt(x.div(y))
        }
        arr.push(result)
      })
      if (!arr || arr.length === 0) {
        stock = 0
      }
      stock = Math.min.apply(null, arr)
      return stock
    },
    // 计算sku所有单品的总价格
    countSkuPrice (skuSingleProds) {
      let price = 0.00
      if (!skuSingleProds) {
        return price
      }
      if (!skuSingleProds.length) {
        return price
      }
      skuSingleProds.forEach(element => {
        var x = new Big(element.total)
        var y = new Big(price)
        price = parseInt(y.plus(x))
      })
      return price
    },
    switchSet () {
      this.isEdit = !this.isEdit
      if (!this.isEdit) {
        this.dataFrom.oriPrice = 0
        this.dataFrom.price = 0
        this.dataFrom.stocks = 0
        this.dataFrom.weight = 0
        this.dataFrom.volume = 0
      }
    },
    batchSet () {
      this.value.forEach(sku => {
        if (this.dataFrom.oriPrice) {
          sku.oriPrice = this.dataFrom.oriPrice
        }
        if (this.dataFrom.price) {
          sku.price = this.dataFrom.price
        }
        if (this.dataFrom.stocks) {
          sku.stocks = this.dataFrom.stocks
        }
        if (this.dataFrom.weight) {
          sku.weight = this.dataFrom.weight
        }
        if (this.dataFrom.volume) {
          sku.volume = this.dataFrom.volume
        }
      })
      this.isEdit = false
    }
  }
}
</script>

<style lang="scss" scoped>

.mod-prod-sku-table {
  .pic-uploader-component .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    .pic-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 120px;
      height: 120px;
      line-height: 120px;
      text-align: center;
    }
    .pic {
      width: 120px;
      height: 120px;
      display: block;
    }
  }
  .pic-uploader-component .el-upload:hover {
    border-color: #409eff;
  }
}

  /deep/ .el-table{
    width: 76.5%;
  }

  // div /deep/ .el-form-item__content span,
  // div /deep/ .mul-pic-upload div {
  //   color: #02A1E9;
  // }
  .filter-submitBtn span{
    color:#fff !important;
  }
div /deep/ .el-table tbody tr:hover>td { background-color: #ffffff }
</style>
